package com.cmc.cloud.cmclink.doc.api.document;

import com.alibaba.nacos.common.utils.ClassUtils;
import com.cmes.framework.common.exception.ErrorCode;
import org.springframework.core.env.StandardEnvironment;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.type.ClassMetadata;
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReader;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 周贤
 * @date 2025/6/17
 */
public class TestObject {

    public static void main(String[] args) throws IOException, ClassNotFoundException, IllegalAccessException {

        String basePackage = "com.cmc.cloud.cmclink.doc.constants.errorconstant";
        String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
                ClassUtils.convertClassNameToResourcePath(new StandardEnvironment().resolveRequiredPlaceholders(basePackage)) + "/" + "**/*.class";
        org.springframework.core.io.Resource[] resources = new PathMatchingResourcePatternResolver().getResources(packageSearchPath);
        System.out.println("# error code 信息");
        for (Resource resource : resources) {
            MetadataReader metadataReader = new CachingMetadataReaderFactory().getMetadataReader(resource);
            ClassMetadata classMetadata = metadataReader.getClassMetadata();

            String className = classMetadata.getClassName();
            Class<?> aClass = Class.forName(className);
            Field[] fields = aClass.getDeclaredFields();
            List<String> props = new ArrayList<>();
            for (Field field : fields) {
                Class<?> type = field.getType();
                if (type == ErrorCode.class) {
                    field.setAccessible(true);
                    ErrorCode o = (ErrorCode) field.get(aClass);
                    props.add(o.getCode() + "=" + o.getMsg());
                }
            }
            if (!props.isEmpty()) {
                System.out.println("# " + aClass.getSimpleName());
                props.forEach(System.out::println);
            }
        }

    }
}
